using UnityEngine;
using System.Collections;

public class ArrowMover : MonoBehaviour
{
    public float moveSpeed = 100f; // 箭头移动速度
    public float slowdownFactor = 0.5f; // 在边缘时的减速因子
    public float blockWidth = 140f; // 每个方块的宽度
    public int blockCount = 5; // 方块数量

    private float leftBound;
    private float rightBound;
    private float direction = 1f; // 1 for right, -1 for left
    private int currentBlockIndex = 2; // 从第3个方块开始（索引从0开始）

    void Start()
    {
        // 计算左右边界
        leftBound = transform.position.x - (blockWidth * 2) - blockWidth * 0.5f;
        rightBound = transform.position.x + (blockWidth * 2) + blockWidth * 0.5f;
    }

    void Update()
    {
        // 计算当前速度
        float currentSpeed = moveSpeed;
        if (IsNearEdge())
        {
            currentSpeed *= slowdownFactor;
        }

        // 移动箭头
        transform.Translate(Vector3.right * direction * currentSpeed * Time.deltaTime);

        // 检查是否需要改变方向
        if (transform.position.x <= leftBound || transform.position.x >= rightBound)
        {
            direction *= -1;
        }

        // 更新当前方块索引
        UpdateCurrentBlockIndex();
    }

    bool IsNearEdge()
    {
        return Mathf.Abs(transform.position.x - leftBound) < blockWidth * 0.5f ||
               Mathf.Abs(transform.position.x - rightBound) < blockWidth * 0.5f;
    }

    void UpdateCurrentBlockIndex()
    {
        float relativePosition = transform.position.x - leftBound;
        currentBlockIndex = Mathf.Clamp(Mathf.FloorToInt(relativePosition / blockWidth), 0, blockCount - 1);
        Debug.Log("Arrow is currently under block: " + currentBlockIndex);
    }

    // 获取当前箭头所在的方块索引（0-4）
    public int GetCurrentBlockIndex()
    {
        return currentBlockIndex;
    }
}